<?php
namespace Common\Model;

class AccountModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
			//新增
			array('user_id', '/^\d+$/', '用户id错误', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
	);
	
	//自动完成
	protected $_auto = array(
			array('create_time', NOW_TIME, 1, 'string'),
			array('update_time', NOW_TIME, 3, 'string'),
			array('status', 1, 1, 'string')
	);
	
	public function addAcc($data)
	{
		//创建数据对象并判断
		if(!$this->create($data)) return array('error' => 1, 'info' => $this->getError());
		$id = $this->add();
		if($id) return array('error' => 0, 'info' => '添加成功');
		return array('error' => 1, 'info' => '添加失败');
	}
	
	/**
	 *  冻结资金
	 * @param float $frozen 冻结金额
	 * @param int $userId 用户ID
	 * @param int $targetId 发生冻结操作的订单ID
	 * @param number $type 
	 * @param array $acc 用户原来账户信息
	 * @return array
	 */
	public function frozen($frozen, $targetId , $userId, $acc = null)
	{
		//判断参数
		if(!$frozen || !$targetId) return array('error' => 1, 'info' => '参数错误');
		
		//判断更新条件
		if(!$userId) return array('error' => 1, 'info' => '操作条件错误');

		//查询账户信息
		if(!$acc) $acc = $this->where(array('user_id' => $userId))->find();
		if(!$acc) return array('error' => 1, 'info' => '用户账户信息获取失败');
		
		$data['enable'] = bcsub($acc['enable'], $frozen, 2);
		$data['frozen'] = bcadd($acc['frozen'], $frozen, 2);
		
		$logData['user_id'] = $userId;
		$logData['target_id'] = $targetId;
		$logData['type'] = 0;
		$logData['note'] = C('ACCOUNT_LOG')[0] . '：冻结资金';
		$logData['amount'] = $frozen;
		
		return $this->updateAccountInternal($data, array('user_id' => $userId), $logData);
	}
	
	private function updateAccountInternal($data, $where, $logData)
	{
		//开启事务
		$this->startTrans();
		
		try {
			//更新 
			$res = $this->where($where)->save($data);
			if(!$res) throw new \Exception('账户更新失败');
			
			//日志
			$res = D('AccountLog')->addLog($logData);
			if($res['error'] === 1) throw new \Exception('账户日志更新失败');
			
			$return = array('error' => 0, 'info' => '');
			$this->commit();
		} catch (\Exception $e) {
			$this->rollback();
			$return = array('error' => 1, 'info' => $e->getMessage());
		}
		
		return $return;
	}
}